from flask import request, jsonify, render_template
from database import get_db_connection

def register_user_routes(app):
    @app.route('/users', methods=['GET'])
    def get_users():
        conn = get_db_connection()
        c = conn.cursor()
        c.execute('SELECT * FROM users')
        users = c.fetchall()
        conn.close()
        user_list = [{'id': user[0], 'name': user[1], 'email': user[2]} for user in users]
        return render_template('users.html', users=user_list)

    @app.route('/add_user', methods=['GET'])
    def add_user():
        return render_template('adduser.html')

    # 新增 /add_user 的 POST 请求处理函数
    @app.route('/add_user', methods=['POST'])
    def new_add_user():
        data = request.get_json()
        name = data.get('name')
        email = data.get('email')
        if not name or not email:
            return jsonify({'error': 'Name and email are required'}), 400
        conn = get_db_connection()
        c = conn.cursor()
        c.execute('INSERT INTO users (name, email) VALUES (?, ?)', (name, email))
        conn.commit()
        new_user_id = c.lastrowid
        conn.close()
        return jsonify({'id': new_user_id, 'name': name, 'email': email}), 201